from flask import current_app
from flask_httpauth import HTTPTokenAuth
from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired)

from common import AuthFailed

auth = HTTPTokenAuth()


def generate_token(user):
    '''
    生成token
    :param expires:失效时间
    :param user:用户id
    :return: token
    '''

    # 第一个参数是内部的私钥，这里写在共用的配置信息里了，如果只是测试可以写死
    # 第二个参数是有效期(秒)
    secret = current_app.config['SECRET_KEY'] or 'xtoad'
    token_expires = current_app.config['TOKEN_EXPIRES'] or 3600
    s = Serializer(secret, expires_in=token_expires)
    # 接收用户id转换与编码
    token = s.dumps({"id": user})

    return str(token, 'utf-8')


@auth.verify_token
def verify_token(token):
    if not token.strip():
        raise AuthFailed('token missed')  # token missed
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
    except SignatureExpired:
        raise AuthFailed('token expired')  # valid token, but expired
    except BadSignature:
        raise AuthFailed('invalid token')  # invalid token

    return data['id']

